const { formatDate } = require('../../utils/dateUtil');

Page({
  clearAllRecords() {
    wx.showModal({
      title: '确认清除',
      content: '确定要清除所有接收记录吗？此操作不可撤销',
      success: (res) => {
        if (res.confirm) {
          this.setData({ isLoading: true });
          try {
            wx.setStorageSync('dataRecords', []);
            this.setData({ 
              records: [],
              isLoading: false
            });
            wx.showToast({ 
              title: '记录已清除', 
              icon: 'success',
              duration: 2000
            });
          } catch (err) {
            console.error('清除记录失败:', err);
            this.setData({ isLoading: false });
            wx.showToast({
              title: '清除失败',
              icon: 'error',
              duration: 2000
            });
          }
        }
      }
    });
  },

  onNavigationBarButtonTap(e) {
    this.clearAllRecords();
  },

  data: {
    records: [],
    isLoading: false
  },

  onLoad() {
    this.loadRecords();
  },

  onShow() {
    this.loadRecords();
  },

  loadRecords() {
    this.setData({ isLoading: true });
    const records = wx.getStorageSync('dataRecords') || [];
    this.setData({ 
      records: records.map(item => {
        const record = {
          ...item,
          time: formatDate(item.time),
          shortText: item.type === 'text' ? 
            (item.content.length > 10 ? item.content.substring(0, 10) + '...' : item.content) : null
        };
        
        if (item.type === 'file') {
          const fileExt = item.fileName.split('.').pop().toLowerCase().trim();
          const isImage = ['jpg','jpeg','png','gif','bmp','webp','svg'].includes(fileExt);
          record.actionText = isImage ? '保存相册' : '打开';
        }
        
        return record;
      }),
      isLoading: false
    });
  },

  copyText(e) {
    const { index } = e.currentTarget.dataset;
    const { content } = this.data.records[index];
    wx.setClipboardData({
      data: content,
      success: () => {
        wx.showToast({ title: '复制成功' });
      }
    });
  },

  async handleFileAction(e) {
    const { index } = e.currentTarget.dataset;
    const record = this.data.records[index];
    
    if (record.type !== 'file') return;
    
    try {
      if (!record.filePath) {
        throw new Error('文件路径不存在');
      }

      const fileExt = record.fileName.split('.').pop().toLowerCase().trim();
      const isImage = ['jpg','jpeg','png','gif','bmp','webp','svg'].includes(fileExt);

      if (isImage) {
        await this.saveImageToAlbum(record.filePath);
      } else {
        await this.openDocument(record.filePath, fileExt);
      }
    } catch (err) {
      console.error('文件操作失败:', err);
      wx.showToast({
        title: '操作失败: ' + err.message,
        icon: 'none'
      });
    }
  },

  async saveImageToAlbum(filePath) {
    await new Promise((resolve, reject) => {
      wx.saveImageToPhotosAlbum({
        filePath,
        success: () => {
          wx.showToast({ title: '图片已保存到相册' });
          resolve();
        },
        fail: (err) => {
          console.error('保存图片失败:', err);
          reject(err);
        }
      });
    });
  },

  async openDocument(filePath, fileType) {
    await new Promise((resolve, reject) => {
      wx.openDocument({
        filePath,
        fileType: 'doc',
        showMenu: true,
        success: resolve,
        fail: (err) => {
          console.error('打开文档失败:', err);
          reject(err);
        }
      });
    });
  },

  onPullDownRefresh() {
    this.loadRecords(() => {
      wx.stopPullDownRefresh();
    });
  }
});